<template>
  <div class="people-container-box common-check-container">
    <div class="common-list-bread">
      <el-button class="common-btn-solid" size="small" @click="onClickCancel"
        >返回</el-button
      >
      <span class="title"
        >{{topTitle[actionType]}}装备</span
      >
    </div>
    <div class="wrapper">
      <div class="task-container  common-detail-box">
        <div>
          <el-form
            :model="detailInfo"
            ref="formDom"
            :rules="rules"
            label-width="190px"
            class="add-form"
          >
         
          <el-form-item label="所属类别："  prop="resourceCategoryId"  class="width-160 active no">
              <el-select  @change="onChangeresourceCategory" v-model="detailInfo.resourceCategoryId"  placeholder="请选择" clearable filterable :popper-append-to-body="false" >
                <el-option v-for="typeValue in resourceTypeList"
                  :key="typeValue.id" :label="typeValue.name"
                  :value="typeValue.id">
                </el-option>
              </el-select>
          </el-form-item>
               <!--  multiple :limit="3" -->
           <el-upload
                class="upload-demo"
                action="/api/common/twoDimensionalUpload"
                :before-remove="beforeRemove"
                :show-file-list="false"
                :on-success="handlesuccess"
                :before-upload="beforeAvatarUpload"
                accept="image/png,image/jpeg,image/jpg,image/gif"
                >
                <el-button  icon="el-icon-upload2" size="small">上传2维文件</el-button>
            </el-upload>
            <el-upload
                class="upload-demo"
                action="/api/common/threeDimensionalUpload"
                multiple
                :show-file-list="false"
                :on-success="handlesuccess2"
                :before-upload="beforeAvatarUpload2"
                accept=".zip"
                >
                <el-button  icon="el-icon-upload2" size="small">上传3维文件</el-button>
            </el-upload>
            <span class="text">3维文件上传支持zip 、rar压缩包，包内需含名为“缩略图.png”的文件作为以下展示用图</span>
            <ImagePreview @deleteImage="onDeleteImage" :fileList='fileList' :curType='1' :fileList2='fileList2'></ImagePreview>
             
            <br>
            
            

            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>


            <el-form-item label="资源名称：" prop="name" class="width-160 active" >
              <el-input
                clearable
                :maxlength="10"
                v-model="detailInfo.name"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
            <el-form-item label="资源代号：" prop="code" class="width-160 active">
              <el-input
                clearable
                :maxlength="10"
                v-model="detailInfo.code"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
            <div style="" class="radio-box">
              <div class="radio-item">
                  <el-form-item label="是否可用："  class="isuse" >
                  <el-radio-group v-model="detailInfo.availableType" @change="onChangeType"> 
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="2">否</el-radio>
                </el-radio-group>
                <el-select v-show="detailInfo.availableType==2" class="other" v-model="detailInfo.availableReasonType"  placeholder="请选择" clearable filterable :popper-append-to-body="false" >
                    <el-option label="损坏" value='1'></el-option>
                    <el-option label="报废" value='2'></el-option>
                    <el-option label="消耗" value='3'></el-option>
                    <el-option label="其他" value='4'></el-option>
                  </el-select>
                  <el-input
                    clearable v-show="detailInfo.availableType==2" 
                    :maxlength="10"
                    v-model="detailInfo.availableReason"
                    placeholder="请填写具体原因"
                  ></el-input>
                </el-form-item>
              </div>
        
              <div class="radio-item">
                <el-form-item label="使用期限："  class="width-160 date-content" >
                  <el-radio-group v-model="detailInfo.expireType" @change="onChangeDate">
                  <el-radio :label="2">短期</el-radio>
                  <el-radio :label="1">长期</el-radio>
                </el-radio-group>
                <br>
                  <div v-show="detailInfo.expireType == 2">
                    <el-date-picker
                      value-format="yyyy-MM-dd"
                      v-model="detailInfo.startDate"
                      type="date"
                      :clearable="false"
                      :editable="false"
                      placeholder="开始日期"
                    >
                    </el-date-picker>
                    至
                    <el-date-picker
                      value-format="yyyy-MM-dd"
                      v-model="detailInfo.endDate"
                      type="date"
                      :clearable="false"
                      :editable="false"
                      placeholder="结束日期"
                    >
                    </el-date-picker>
                  </div>
              </el-form-item>
              </div>
            </div>
           
              <el-form-item :key="idx" v-for="(item,idx) in workAttributeVoList" :label="item.attributeName+'：'"  class="width-160 active" >
                <el-input
                  clearable
                  :maxlength="10"
                  v-model="item.attributeValue"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
              <br>
              <el-form-item :key="idx" v-for="(item,idx) in attributeVoList" :label="item.attributeName+'：'"  class="width-160 active" >
                <el-input
                  clearable
                  :maxlength="10"
                  v-model="item.attributeValue"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
              <br>
              <el-form-item label="总数量：" class="width-160 active" >
              <el-input
                clearable
                :maxlength="10"
                v-model.number="totalEquipment"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
            <el-form-item label="已用数量：" class="width-160 active">
              <el-input
                clearable
                :maxlength="10"
                v-model.number="useEquipment"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          
            
            <el-form-item label="资源标签：" class="desc" style="width:738px;">
             <el-checkbox-group v-model="checkList">
              <el-checkbox :label="item.name" :key="idx" v-for="(item,idx) in checkListData"></el-checkbox>
            </el-checkbox-group>
            </el-form-item>
            <el-form-item label="资源描述：" class="desc">
              <el-input
                type="textarea"
                :maxlength="300"
                :autosize="{ minRows: 5 }"
                v-model="detailInfo.describe"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="common-footer">
      <el-button class="common-btn-primary" @click="onClickSaveData"
        >保存</el-button
      >
      <el-button class="common-btn-solid" @click="onClickCancel"
        >取消</el-button
      >
    </div>
    </div>
    
  </div>
</template>
<script>
import { ref, reactive, onMounted,toRefs,watch,nextTick } from "@vue/composition-api";
// import ImagePreview from "components/ImagePreview";
export default {
  /* components:{
    ImagePreview
  }, */
   setup(props, { root } ){  
     let formDom = ref(null);
     let topTitle = ref({'add':'添加','edit':'编辑','copy':'复制'});
    //  console.log(root.$route)
     let datas = reactive({
        id:'',//编辑Id
        workSetType:false,//工作部署
        queryParams: {}, //列表页查询参数
        resourceType: 2, //所属模块1=实验人员 2=实验装备 3=实验场地 4=被测装备
      

        detailInfo:{
          code: "", //试验代号
          name: "", //类别名称
          describe: "", //资源描述
          resourceCategoryId: "", //所属类别

          availableType:1,//是否可用
          availableReasonType:'',// 不可用原因类型
          availableReason:'',// 不可用原因

          expireType:1,// 使用期限类型
          startDate:'',// 开始时间
          endDate:'',// 	结束时间 
        },
        totalEquipment: '', //总数
        useEquipment: '', //已使用数量
        resourceTagDoList: [], //资源标签集合
        resourceTagDoList: [], //资源标签集合
        attributeVoList: [{ //	类别动态属性集合
          "attributeName": "属性名称1(标签1)",
          "attributeValue": 1
        }],
        workAttributeVoList: [ {//	工作部署属性集合
          "attributeName": "工作(标签1)",
          "attributeValue": 1
        },{//	工作部署属性集合
          "attributeName": "工作(标签2)",
          "attributeValue": 2
        },{//	工作部署属性集合
          "attributeName": "工作(标签3)",
          "attributeValue": 3
        },{//	工作部署属性集合
          "attributeName": "工作(标签4)",
          "attributeValue": 4
        },{//	工作部署属性集合
          "attributeName": "工作(标签5)",
          "attributeValue": 5
        }], 

       
        actionType: '', //区分编辑 新增 
        rules: {
          name: [
            {
              required: true,
              message: "请输入资源名称",
              trigger: ["blur"],
            },
          ],
          code: [
            {
              required: true,
              message: "请输入资源代号",
              trigger: ["blur"],
            },
          ],
        
          resourceCategoryId: [
            {
              required: true,
              message: "请选择所属类别",
              trigger: ["change"],
            },
          ]
        },


         resourceTypeList:[],//类别集合
         checkList:[],//选中资源标签集合
         checkListData:[],//资源标签集合

        dialogImageUrl: '',
        dialogVisible: false,
        fileList: [{
          name: 'food.jpeg',
          url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
          ,ischecked: false
        }, {
           name: 'food2.jpeg', 
           url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
          ,ischecked: true
           }],
        fileList2: [{
          name: 'food.jpeg',
          url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
          ,ischecked: false
        },{
          name: 'food.jpeg',
          url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
          ,ischecked: false
        },{
          name: 'food.jpeg',
          url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
          ,ischecked: false
        },{
          name: 'food.jpeg',
          url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
          ,ischecked: false
        }]
     
         
     });

   
    
    /**
     * @desc 上传图片成功后的回调
     * @param response {object} 接口响应
     * @param file {object} 当前文件详情
     * @param fileList {Array} 最新结果集合
     * 
     */
     const handlesuccess = (response, file, fileList)=> {
        console.log('上传成功');
        // console.log(response,file, fileList);
        root.imageUrl = URL.createObjectURL(file.raw);
        console.log(root.imageUrl);

        datas.fileList.push({
           name: file.name, 
           url: root.imageUrl, 
           ischecked: false
        })
      };
      //图片上传前限制校验
     const beforeAvatarUpload = (file)=> {
        const isLt5M = file.size / 1024 / 1024 < 5;
        if (!isLt5M) {
          root.$message.error('上传图片大小不能超过 5MB!');
        }
        return isLt5M;
      };
      //3D上传前限制校验
     const beforeAvatarUpload2 = (file)=> {
        console.log('3D上传前限制校验');
        console.log(file);
        const isLt20M = file.size / 1024 / 1024 < 20;
        if (!isLt20M) {
          root.$message.error('上传模型大小不能超过 20MB!');
        }
        return isLt20M;
      };
      //3D上传回调
     const handlesuccess2 = (response, file, fileList)=> {
        console.log('上传成功');
        console.log(response,file, fileList);
       /*  root.imageUrl = URL.createObjectURL(file.raw);
         console.log(root.imageUrl);
        datas.fileList2.push({
           name: file.name, 
           url: root.imageUrl, 
           ischecked: false
        }) */
      };
     
     const onDeleteImage = ({idx,type})=> {
        console.log(idx,type);
         if(type === 1) {
            datas.fileList.splice(idx,1)
          } else {
            datas.fileList2.splice(idx,1)
          }
      };
     
  

      //回显数据
     const asyncGetDetailData = (id)=> {
      root.$axios.get("/baseresource/getBaseResourceById?id=" +id)
          .then((res) => {
          if (res.data.code === 200) {
            const data = res.data.data;
            Object.keys(data).forEach((item) => {
              datas.detailInfo[item] = data[item];
            });
            // datas.workSetType = data.workSetType === 1 ? true : false;

            ///???
            /* datas.attributeVoList = data.attributeVoList|| [];
            datas.workAttributeVoList = data.workAttributeVoList|| []; */
            
          } else {
            root.$message.error(res.data.msg);
          }
        });
    }
    //切换--类别获取属性集合
     const onChangeresourceCategory = (id)=> {
       console.log(id)
       asyncGetAttributetList(id);
    }  
   
    //切换--是否可用
     const onChangeType = (v)=> {
       console.log(v)
    }
    //切换--使用期限
     const onChangeDate = (v)=> { 
       console.log(v)
    }
    //点击--模块类型
     const onChangeModule = (val)=> {
       console.log(val)
      //  asyncGetTagList(val);
    }
    //获取--资源标签集合
    const asyncGetTagList = (val)=>{
      root.$axios.get("/resourcecategory/listResourceTag?resourceType="+val)
      .then((res) => {
        if (res.data.code === 200) {
          datas.checkListData =  res.data.data || [];
        } else {
          root.$message.error(res.data.msg);
        }
      });
    }
  
    //获取--类别下拉集合 
    const asyncGetResourceTypeList = (val)=>{
      root.$axios.get("/baseresource/getResourceCategoryListByType?resourceType="+val)
      .then((res) => {
        if (res.data.code === 200) {
          datas.resourceTypeList  =  res.data.data  || [];
        } else {
          root.$message.error(res.data.msg);
        }
      });
    }
    //获取--动态属性集合
    const asyncGetAttributetList = (id)=>{
      root.$axios.get("/baseresource/listAttributeCategoryById?categoryId="+id)
      .then((res) => {
        if (res.data.code === 200) {
          let data = res.data.data;
          datas.attributeVoList  =  data.attributeVoList  || [];
          datas.workAttributeVoList  =  data.workAttributeVoList  || [];
        } else {
          root.$message.error(res.data.msg);
        }
      });
    }
    
    //
    //点击取消
     const onClickCancel = ()=> {
      root.$router.push({
        path: "/experimentsPlace",
        // query: this.queryParams
      });
    }
    //点击保存
     const onClickSaveData = ()=> {
      formDom.value.validate((valid) => {
        if (valid) {
          if(datas.detailInfo.expireType === 2) {
            if ((!datas.detailInfo.startDate && !datas.detailInfo.endDate) || (!datas.detailInfo.startDate && datas.detailInfo.endDate) 
            || (datas.detailInfo.startDate && !datas.detailInfo.endDate)) {
              root.$message.error('请完善时间填写');
              return;
            } else if( datas.detailInfo.startDate && datas.detailInfo.endDate && datas.detailInfo.startDate > datas.detailInfo.endDate) {
              root.$message.error('请开始时间不能大于结束时间');
              return;
            } 
          }
          if (isNaN(datas.totalEquipment)) {
              root.$message.error('总数量字段格式为数字类型');
              return;

          }
          if (isNaN(datas.useEquipment)) {
              root.$message.error('已用数量字段格式为数字类型');
              return;
          }
          if (datas.useEquipment > datas.totalEquipment) {
              root.$message.error('已用数量必须小于总数量');
              return;
          }
          const url =
            datas.actionType !== "edit"
              ? "/baseresource/saveBaseResource"
              : "/baseresource/updateBaseResource";
          const id =
            datas.id && datas.actionType === "edit"
              ? datas.id
              : "";
              const data = {
                 ...datas.detailInfo,
                 id,
                  resourceTagNames:datas.checkList.join(','),
                  resourceType:datas.resourceType,
                  useEquipment:datas.useEquipment,
                  totalEquipment:datas.totalEquipment,



                  attributeVoList:datas.attributeVoList,
                  workAttributeVoList:datas.workAttributeVoList
              }

              console.log(data)

          asyncSaveData(url, data);
        }
      });
    }

    //保存数据
   const asyncSaveData = (url, data)=> {
      root.$axios
        .post(url, data)
        .then((res) => {
          if (res.data.code === 200) {
            onClickCancel();
          } else {
            root.$message.error(res.data.msg);
          }
        });
    }

    
     onMounted(()=>{
       nextTick(()=>{
          console.log(root)
       })
     })


     


    

     datas.actionType = root.$route.params.action;
     datas.id = root.$route.query.currentTabId;

     console.log(root.$route.params.action)
     console.log(root.$route.query)
     console.log(topTitle.value[datas.actionType])

     asyncGetResourceTypeList(2);
     
     if (datas.actionType === "edit" || datas.actionType === "copy") {
      asyncGetDetailData(datas.id);
    } else {
      asyncGetTagList(2);
    }

     return {
          ...toRefs(datas),detailInfo:datas.detailInfo,topTitle,
          asyncGetAttributetList, onChangeresourceCategory, onChangeDate,
          onChangeType,onClickCancel,onClickSaveData,formDom,onChangeModule,
          handlesuccess,handlesuccess2,onDeleteImage,
          beforeAvatarUpload,beforeAvatarUpload2
     }
   },

};
</script>
<style scoped>
.people-container-box {
  padding: 0;
  /* background-color: #fff; */
}
.people-container-box .common-detail-box {
  padding: 40px 0 0 0;
}
.people-container-box /deep/ .el-input__inner {
  height: 32px;
  line-height: 32px;
}
.people-container-box /deep/ .equipment .el-select,
.people-container-box /deep/ .theme .el-input,
.people-container-box /deep/ .desc .el-textarea {
  width: 80%;
}
.upload-content {
  width: 52%;
  margin-bottom: 5px;
}
.people-container-box /deep/ .desc {
  margin-bottom: 12px;
}
.upload-tip {
  height: 22px;
  line-height: 25px;
  font-size: 13px;
  color: #888888;
}
.people-container-box .width-160 /deep/ .el-input {
  width: 160px;
}
.people-container-box .width-160.active {
  display:inline-block;
  margin-right: 26px;
}
.people-container-box .width-160.active.no {
  margin-right: 5px;
}

.item-score {
  position: relative;
  display: inline-block;
  margin-left: 30px;
}
.title {
  padding-left: 10px;
}
.task-container {
  padding-top: 20px;
  background-color: #fff;
  /* overflow-y: auto; */
}
.wrapper {
  overflow-y: auto;
}
.desc-text {
  font-size: 12px;
  color: #A3A3A3;
  line-height: 20px;
}

 
.del-content {
   padding-left: 20px;
   cursor: pointer;
}
.del-text {
   color:#6B8CED;
}
.add-tag-btn {
  margin-left: 10px;
}
.checkbox-item {
  display: inline-block;
  position: relative;
  margin-right: 10px;
}
.checkbox-item >>> .el-checkbox {
  margin-right: 0;
}
.close {
  position: absolute;
  cursor: pointer;
  top: 13px;
  right: 4px;
  font-size: 15px;
}
.close:hover {
  opacity: .8;
}



.other {
  width:86px;
}
.other >>> .el-input{
    width: 92px;
    margin-left: 10px;
}
.date-content {
  margin-left: -23px;
}
.add-form{
  padding-bottom: 30px;
  max-width: 1090px;
  /* max-width: 1046px; */
  margin: 0 auto;
  /* overflow: hidden; */
}
.add-form >>> .el-cascader__suggestion-panel{
  width:160px;
}
.isuse >>> .el-form-item__content {
    width: 208px;
}
.radio-box {
  display:flex;
}
.radio-item {
  display: inline-block;
}
.upload-demo {
  display: inline-block;
  margin: 0 5px;
}
/* .upload-demo >>> .el-upload-list {
  display: none;
} */
.text {
  font-size: 12px;
  color:#BFBFBF;
}
/* 展示图片内容  start*/
/* .upload-list{
  margin-left: 190px;
}

.upload-list-item {
  width: 160px;
  height: 160px;
  display: inline-block;
  border:1px solid #ccc;
  border-radius:5px;
  margin-right: 8px;
}
.upload-list-item.active {
  border-color: #4972E8;
}
.list-item-content {
  width: 160px;
  height: 160px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}
.item-top {
  display: flex;
  padding: 10px;
  justify-content: space-between;
}
.item-bottom {
  height: 119px;
  width: 158px;
  overflow: hidden;
  position: relative;
}
.item-bottom .img{
  width: 158px;
  height: 119px;
  object-fit: cover;
}

.mark {
  position: absolute;
  width:100%;
  height:100%;
  background: rgba(0,0,0,.6);
  left: 0;
  top: 0;
  display:none;
}
.item-bottom:hover .mark{
  display:block;
}
.el-upload-list__item-actions-content{
    position: absolute;
    top: 47px;
    width: 86%;
    color: #fff;
    font-size: 20px;
    display:none;
}
.el-upload-preview {
  padding: 0 50px 0 36px;
}
.item-bottom:hover .el-upload-list__item-actions-content{
  cursor: pointer;
  display:block;
}

.item-bottom .default{
    width: 73px;
    height: 92px;
    margin: 0 auto;
    display: block;
}
.item-bottom .icon-3d{
    position: relative;
    width: 22px;
    top: 3px;
} */
/* 展示图片内容  end*/

</style>
<style>
/*  .people-container-box .width-160 .el-input {
    width: 160px;
  } */
.el-popover .el-popconfirm__action {
   padding-top: 15px;
}
</style>
